package com.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC {

    public static void main(String[] args) throws InterruptedException {

        Cycle c= new Cycle(15);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        threadPoolExecutor.submit(() ->{
            c.printA();
        });
        threadPoolExecutor.submit(() ->{
            c.printB();
        });
        threadPoolExecutor.submit(() ->{
            c.printc();
        });
        threadPoolExecutor.shutdown();
    }
}


class Cycle{

    Lock lock = new ReentrantLock();
    Condition printa = lock.newCondition();
    Condition printb = lock.newCondition();
    Condition printc = lock.newCondition();

    //
    int  k = 0;
    int count;

    public Cycle(int count) {
        this.count = count;
    }

    public void printA(){
        for(int i = 0;i < count;i++){
            lock.lock();
            try {
                while (k != 0){
                    printa.await();
                }
                System.out.println(i+":"+"A");
                k++;
                printb.signal();

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public void printB(){
        for(int i = 0;i < count;i++){
            lock.lock();
            try {
                while (k != 1){
                    printb.await();
                }
                System.out.println(i+":"+"B");
                k++;
                printc.signal();

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public void printc(){
        for(int i = 0;i < count;i++){
            lock.lock();
            try {
                while (k != 2){
                    printc.await();
                }
                System.out.println(i+":"+"C");
                k = 0;
                printa.signal();

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

}
